<template>
	<view class="page mine-edit">
		<uni-forms ref="form" :modelValue="userInfo" label-position="top" label-width="100%">
			<uni-forms-item label="头像:" name="headImage">
				
				<image :src="userInfo.headImage" @click="selectAndUpload"></image>
			</uni-forms-item>
			<uni-forms-item label="用户名:" name="username">
				<uni-easyinput type="text" v-model="userInfo.username" :disabled="true" />
			</uni-forms-item>
			<uni-forms-item label="昵称:" name="nickname">
				<uni-easyinput v-model="userInfo.nickname" type="text" :placeholder="userInfo.username" />
			</uni-forms-item>
		
		</uni-forms>
		<button type="primary" @click="onSubmit()">提交</button>
	</view>
</template>

<script>
	import UNI_APP from '@/.env.js'
	const baseUrl = UNI_APP.BASE_URL
	const baseChatUrl = UNI_APP.BASE_IM_URL
	export default {
		data() {
			return {
				userInfo: {}
			}
		},
		methods: {
			selectAndUpload() {
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数，默认9
					sourceType: [this.sourceType], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					sizeType: ['original'], //original 原图，compressed 压缩图，默认二者都有
					success: (res) => {
						console.log(res)

						this.userInfo.headImage = res.tempFilePaths[0]
						this.userInfo.headImageThumb = res.tempFilePaths[0]

					},
					fail: (err) => {
						uni.showToast({
							title: "图片上传失败",
							icon: 'none'
						})
					}
				})
			},
		uploadHeadImage(){
				return new Promise((resolve,reject)=>{
					uni.uploadFile({
						url: UNI_APP.BASE_URL + '/file/uploadImage/headImage',
						header: {
							accessToken: uni.getStorageSync("loginInfo").accessToken,
							'content-type': 'multipart/form-data'
						},
						filePath: this.userInfo.headImage, // 要上传文件资源的路径
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							console.log("fileData", res,data)
							this.userInfo.headImage = data.data.originUrl
							this.userInfo.headImageThumb = data.data.thumbUrl
							resolve()
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			 onSubmit() {
				if(this.userInfo.headImage.includes("tmp")){
					this.uploadHeadImage().then(()=>{
						this.$http({
							url:  baseUrl+"/user/update",
							method: "PUT",
							data: this.userInfo
						}).then(()=>{
							this.$store.commit("setUserInfo",this.userInfo);
							uni.showToast({
								title:"修改成功",
								icon: 'none'
							});
						})	
					})
				}
				this.$http({
					url:  baseUrl +"/user/update",
					method: "PUT",
					data: this.userInfo
				}).then(()=>{
					this.$store.commit("setUserInfo",this.userInfo);
					uni.showToast({
						title:"修改成功",
						icon: 'none'
					});
				})	

			}
		},
		onLoad() {
			// 深拷贝一份数据
			let mine = this.$store.state.userStore.userInfo;
			this.userInfo = JSON.parse(JSON.stringify(mine));
		}
	}
</script>

<style scoped lang="scss">
	.mine-edit {
		padding: 20rpx;

		.head-image {
			width: 200rpx;
			height: 200rpx;
		}
	}
</style>